package com.wangyang.controller;

import com.wangyang.pojo.Result;
import com.wangyang.pojo.User;
import com.wangyang.service.UserService;
import jakarta.validation.constraints.Pattern;
import org.apache.ibatis.annotations.Param;

import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Validated
@Controller
@ResponseBody
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") @Param("username") String username, @Pattern(regexp = "^\\S{5,16}$") @Param("password") String password){
        Result result = userService.register(username, password);
        return result;
    }

    @PostMapping("login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") @Param("username") String username, @Pattern(regexp = "^\\S{5,16}$") @Param("password") String password){
        Result result = userService.login(username, password);
        return result;
    }

    @GetMapping("userInfo")
    public Result userInfo(){
        Result result = userService.getUserInfo();
        return result;
    }

    @PutMapping("update")
    public Result update(@RequestBody @Validated User user){
        Result result = userService.updateUserInfo(user);
        return result;
    }

    @PatchMapping("updateAvatar")
    public Result updateAvatar(@Param("avatarUrl") @URL String avatarUrl){
        return userService.updateUserPic(avatarUrl);
    }

    @PatchMapping("updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map){
        String oldpwd = map.get("old_pwd");
        String newpwd = map.get("new_pwd");
        String repwd = map.get("re_pwd");
        return userService.updateUserPassword(oldpwd, newpwd, repwd);
    }
}
